﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Model;
using System.Data;
using NBear.Mapping;
using DotNet.Utilities;
using KingRoad.EPM.Web.Util;
//using KingRoad.EPM.InvestmeEntity;

using KingRoad.EPM.Common.Helper;
using DotNet.Model.MyEntity;
using DotNet.Service;
using KingRoad.EPM.Web.ViewModels;

namespace KingRoad.EPM.Web.Areas.Permission.Controllers
{
    /// <summary>
    /// 组织机构管理
    /// 功能描述：组织机构(公司、部门、岗位、职员)的增删改查、移动
    /// 模块负责人：苏千军
    /// 完成日期：2011.9.23
    /// </summary>
    public class OrganizeController : Controller
    {
        //
        // GET: /Permission/Organize/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 组织机构的详情
        /// </summary>
        /// <param name="id">组织机构id</param>
        /// <returns></returns>
        public ActionResult OrganizeDetails(int id)
        {
            Base_Organize module = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(id.ToString());
            ViewBag.ParentName = module.ParentId == null || module.ParentId == 0 ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(module.ParentId.ToString()).FullName;
            return View(module);
        }
        /// <summary>
        /// 岗位详情
        /// </summary>
        /// <param name="id">岗位id</param>
        /// <returns></returns>
        public ActionResult DutyDetails(string id)
        {
            ViewBag.DutyId = id;
            return View();
        }

        /// <summary>
        /// 获得组织机构树
        /// </summary>
        /// <param name="id">标识：0代表组织机构树不含职员节点，1代表含职员节点</param>
        /// <returns>json数据</returns>
        public ActionResult GetOrganizeNodes(int id)
        {
            List<OrganizeDutyEntity> list = ServiceManager.Instance.OrganizeService.GetOrganizeTree(id.ToString()) as List<OrganizeDutyEntity>;
            //foreach (OrganizeDutyEntity info in list)
            //{
            //    if (info.Mark == "Duty")
            //        info.iconSkin = "iCandyStaff";
            //    if (info.Mark == "Department")
            //        info.iconSkin = "iCandyDuty";
            //}
            return Json(list);
        }
        #region 添加组织机构中的公司
        // GET: /Permission/Organize/Create

        public ActionResult Create(int id)
        {
            ViewBag.ID = id;
            ViewBag.Flag = "Create";
            ViewBag.ParentName = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(id.ToString()).FullName;
            return View();
        }

        //
        // POST: /Permission/Organize/Creating

        [HttpPost]
        public ActionResult Creating(Base_Organize model)
        {
            string statuCode = string.Empty;
            string statuMessage = string.Empty;
            OrganizeDutyEntity ode = new OrganizeDutyEntity();
            if (ModelState.IsValid)//实体验证
            {
                model.Bank = "Company";
                model.IsInnerOrganize = 1;
                model.DeletionStateCode = 0;
                
                string id = ServiceManager.Instance.OrganizeService.AddOrganize(model, out statuCode, out statuMessage);
                //若添加人不为管理员，则添加该公司的添加人角色权限（人没有） WS 2011.11.19
                if (statuCode == "OKAdd" && !UserService.CurrUserInfo.IsAdministrator)
                {
                    string state = string.Empty;
                    string Message = string.Empty;
                    int curRoleID = ServiceManager.Instance.RoleService.GetRoleID();
                    if (curRoleID != 0)
                        ServiceManager.Instance.RoleService.GrantRoleOrganizeScopes(curRoleID.ToString(), id, out state, out Message);
                }
                //构造组织机构树需要的机构岗位实体
                ode.Id = "C_" + id;
                ode.ParentId = "C_" + model.ParentId;
                ode.Name = model.FullName;
                ode.Mark = "Company";
                ode.iconSkin = "iCandyCompany";
                ode.Type = "1";
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode == "OKAdd" ? "200" : "300",
                callbackType = "Create",
                data = ode
            });
        }

        //编辑组织机构中的公司、部门
        // GET: /Permission/Organize/Edit/5

        public ActionResult Edit(int id)
        {
            Base_Organize module = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(id.ToString());
            ViewBag.Flag = "Edit";
            ViewBag.ParentName = module.ParentId == null || module.ParentId == 0 ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(module.ParentId.ToString()).FullName;

            return View("Create", module);
        }

        //
        // POST: /Permission/Organize/Edit/5

        [HttpPost]
        public ActionResult Editing(Base_Organize model)
        {
            string statuCode = string.Empty;
            string statuMessage = string.Empty;
            OrganizeDutyEntity ode = new OrganizeDutyEntity();
            if (ModelState.IsValid)//实体验证
            {
                model.Bank = "Company";
                model.IsInnerOrganize = 1;
                model.DeletionStateCode = 0;
                ServiceManager.Instance.OrganizeService.EditOrganiz(model, out statuCode, out statuMessage);
                //构造组织机构树需要的机构岗位实体
                ode.Id = "C_" + model.Id;
                ode.ParentId = "C_" + model.ParentId;
                ode.Name = model.FullName;
                ode.Mark = "Company";
                ode.iconSkin = "iCandyCompany";
                ode.Type = "1";
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode == "OKUpdate" ? "200" : "300",
                callbackType = "Edit",
                data = ode
            });
        }
        #endregion
        #region 添加组织机构中的部门
        // GET: /Permission/Organize/CreateDep 

        public ActionResult CreateDep(int id)
        {
            ViewBag.ID = id;
            ViewBag.Flag = "Create";
            ViewBag.ParentName = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(id.ToString()).FullName;
            return View();
        }

        //
        // POST: /Permission/Organize/DepCreating

        [HttpPost]
        public ActionResult DepCreating(Base_Organize model)
        {
            string statuCode = string.Empty;
            string statuMessage = string.Empty;
            OrganizeDutyEntity ode = new OrganizeDutyEntity();
            if (ModelState.IsValid)//实体验证
            {
                model.Bank = "Department";
                model.IsInnerOrganize = 1;
                model.DeletionStateCode = 0;
                string id = ServiceManager.Instance.OrganizeService.AddOrganize(model, out statuCode, out statuMessage);
                //构造组织机构树需要的机构岗位实体
                ode.Id = "C_" + id;
                ode.ParentId = "C_" + model.ParentId;
                ode.Name = model.FullName;
                ode.Mark = "Department";
                ode.iconSkin = "iCandyCompany";
                ode.Type = "1";
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode == "OKAdd" ? "200" : "300",
                callbackType = "Create",
                data = ode
            });
        }

        //编辑组织机构中的公司、部门
        // GET: /Permission/Organize/EditDep/5

        public ActionResult EditDep(int id)
        {
            Base_Organize model = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(id.ToString());
            ViewBag.Flag = "Edit";
            ViewBag.ParentName = model.ParentId == null || model.ParentId == 0 ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(model.ParentId.ToString()).FullName;
            return View("CreateDep", model);
        }

        //
        // POST: /Permission/Organize/DepEditing/5

        [HttpPost]
        public ActionResult DepEditing(Base_Organize model)
        {
            string statuCode = string.Empty;
            string statuMessage = string.Empty;
            OrganizeDutyEntity ode = new OrganizeDutyEntity();
            if (ModelState.IsValid)//实体验证
            {
                model.Bank = "Department";
                model.IsInnerOrganize = 1;
                model.DeletionStateCode = 0;
                ServiceManager.Instance.OrganizeService.EditOrganiz(model, out statuCode, out statuMessage);
                //构造组织机构树需要的机构岗位实体
                ode.Id = "C_" + model.Id;
                ode.ParentId = "C_" + model.ParentId;
                ode.Name = model.FullName;
                ode.Mark = "Department";
                ode.iconSkin = "iCandyCompany";
                ode.Type = "1";
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode == "OKUpdate" ? "200" : "300",
                callbackType = "Edit",
                data = ode
            });
        }
        #endregion

        #region 添加组织机构中的岗位
        // GET: /Permission/Organize/CreateDuty

        //public ActionResult CreateDuty(string id)
        //{
        //    ViewBag.ID = id.Substring(2);
        //    ViewBag.Flag = "Create";
        //    if (id.StartsWith("C_"))//该岗位的父节点是部门，那他所在部门也就是其父节点
        //    {
        //        Base_Organize org = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(id.Substring(2));
        //        ViewBag.ParentName = org.FullName;
        //        ViewBag.OrganizeID = id.Substring(2);
        //        ViewBag.OrganizeName = org.FullName;
        //        ViewBag.OrganizeFlag = "1";
        //    }
        //    else if (id.StartsWith("D_"))
        //    {
        //        Base_Duty duty = ServiceManager.Instance.OrganizeService.GetDutyEntityById(id.Substring(2));
        //        Base_Duty parentDuty = ServiceManager.Instance.OrganizeService.GetDutyEntityById(duty.ParentId.ToString());
        //        ViewBag.ParentName = duty.Name;
        //        ViewBag.OrganizeID = duty.OrganizeId;
        //        ViewBag.OrganizeName = parentDuty.OrganizeId == 0 || parentDuty.OrganizeId == null ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(parentDuty.OrganizeId.ToString()).FullName;
        //        ViewBag.OrganizeFlag = "0";
        //    }
        //    return View();
        //}

        //
        // POST: /Permission/Organize/DutyCreating

        //[HttpPost]
        //public ActionResult DutyCreating(Base_Duty model, int FromOrganize)
        //{
        //    string statuCode = string.Empty;
        //    string statuMessage = string.Empty;
        //    OrganizeDutyEntity ode = new OrganizeDutyEntity();
        //    if (ModelState.IsValid)//实体验证
        //    {
        //        //if(model.ParentId)
        //        model.DeletionStateCode = 0;
        //        model.IsParentOrg = FromOrganize == 1;//是否岗位的父节点来自组织机构
        //        string id = UserCenter.ServiceManager.Instance.OrganizeService.AddDuty(model, out statuCode, out statuMessage);
        //        //构造组织机构树需要的机构岗位实体
        //        ode.Id = "D_" + id;
        //        ode.ParentId = FromOrganize == 1 ? "C_" + model.ParentId : "D_" + model.ParentId;
        //        ode.Name = model.Name;
        //        ode.Mark = "Duty";
        //        ode.Type = "2";
        //    }
        //    return Json(new CallbackStatus
        //    {
        //        message = statuMessage,
        //        statusCode = statuCode == "OKAdd" ? "200" : "300",
        //        callbackType = "Create",
        //        data = ode
        //    });
        //}

        //编辑组织机构中的岗位
        // GET: /Permission/Organize/DutyEdit/5

        //public ActionResult DutyEdit(string id)
        //{
        //    Base_Duty module = ServiceManager.Instance.OrganizeService.GetDutyEntityById(id.Substring(2));
        //    ViewBag.Flag = "Edit";
        //    if (module.IsParentOrg)//该岗位的父节点是部门，那他所在部门也就是其父节点
        //    {
        //        Base_Organize org = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(module.OrganizeId.ToString());
        //        ViewBag.ParentName = module.ParentId == 0 ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(module.ParentId.ToString()).FullName;
        //        ViewBag.OrganizeName = module.OrganizeId == 0 ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(module.OrganizeId.ToString()).FullName;
        //        ViewBag.OrganizeFlag = "1";
        //    }
        //    else
        //    {
        //        Base_Duty duty = ServiceManager.Instance.OrganizeService.GetDutyEntityById(module.ParentId.ToString());
        //        ViewBag.ParentName = module.ParentId == 0 ? "" : ServiceManager.Instance.OrganizeService.GetDutyEntityById(duty.ParentId.ToString()).Name;
        //        ViewBag.OrganizeID = duty.OrganizeId;
        //        ViewBag.OrganizeName = duty.OrganizeId == 0 ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(module.OrganizeId.ToString()).FullName;
        //        ViewBag.OrganizeFlag = "0";
        //    }
        //    return View("CreateDuty", module);
        //}

        //
        // POST: /Permission/Organize/DutyEditing/5

        //[HttpPost]
        //public ActionResult DutyEditing(Base_Duty model, int FromOrganize)
        //{
        //    string statuCode = string.Empty;
        //    string statuMessage = string.Empty;
        //    OrganizeDutyEntity ode = new OrganizeDutyEntity();
        //    if (ModelState.IsValid)//实体验证
        //    {
        //        //if(model.ParentId)
        //        model.DeletionStateCode = 0;
        //        model.IsParentOrg = FromOrganize == 1;//是否岗位的父节点来自组织机构
        //        int id = UserCenter.ServiceManager.Instance.OrganizeService.EditDudy(model, out statuCode, out statuMessage);
        //        //构造组织机构树需要的机构岗位实体
        //        ode.Id = "D_" + model.ID;
        //        ode.ParentId = FromOrganize == 1 ? "C_" + model.ParentId : "D_" + model.ParentId;
        //        ode.Name = model.Name;
        //        ode.Mark = "Duty";
        //        ode.Type = "2";
        //    }
        //    return Json(new CallbackStatus
        //    {
        //        message = statuMessage,
        //        statusCode = statuCode,
        //        callbackType = "Edit",
        //        data = ode
        //    });
        //}
        #endregion
        #region 职员的添加与编辑
        //添加组织机构中的职员
        // GET: /Permission/Organize/CreateStaff

        public ActionResult CreateStaff(string id)
        {
            //修改为接收公司主键、部门主键、岗位主键并传给前端
            //部门名称、岗位名称也传递过来 WS 2011.10.24
            if (!String.IsNullOrEmpty(Request["dutyId"]))
            {
                string dutyId = Request["dutyId"].Substring(2);
                int indexP = dutyId.IndexOf('_');
                ViewBag.DutyId = dutyId.Substring(0, dutyId.Length - indexP - 1);
                ViewBag.dutyName = ServiceManager.Instance.OrganizeService.GetDutyEntityById(dutyId.Substring(0, dutyId.Length - indexP - 1)).Name;
            }
            if (!String.IsNullOrEmpty(Request["departId"]))
                ViewBag.DepartmentId = Request["departId"].Substring(2);
            ViewBag.departName = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(Request["departId"].Substring(2)).FullName;
            if (!String.IsNullOrEmpty(Request["companyId"]))
            {
                ViewBag.CompanyId = Request["companyId"].Substring(2);
                ViewBag.CompanyName = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(Request["companyId"].Substring(2)).FullName;
            }
            ViewBag.Flag = "Create";
            List<Base_Gender> sexList;
            List<Base_Title> titleList;
            DropDownData(out sexList, out titleList);
            ViewBag.GenderList = sexList;
            ViewBag.TitleList = titleList;
            List<Base_Role> roleList = ServiceManager.Instance.RoleService.GetDT();
            ViewBag.rolelist = roleList;
            return View();
        }
        //填充下拉框数据
        private void DropDownData(out List<Base_Gender> sexList, out List<Base_Title> titleList)
        {
            //TODO:下拉框前台统一 改
            //处理性别下拉框数据
            List<Base_Gender> list = new List<Base_Gender>();
            Base_Gender sex = new Base_Gender();
            sex.GID = "1"; sex.Gname = "男";
            list.Add(sex);
            sex = new Base_Gender();
            sex.GID = "0"; sex.Gname = "女";
            list.Add(sex);
            sexList = list;
            //处理职务下拉框数据
            titleList = ServiceManager.Instance.OrganizeService.GetItemTitle() as List<Base_Title>;
        }
        //新增职员的提交处理
        // POST: /Permission/Organize/StaffCreating
        [HttpPost]
        public ActionResult StaffCreating(DotNet.Model.MyEntity.Base_Staff model)
        {
            string statuCode = string.Empty;
            string statuMessage = string.Empty;
            if (ModelState.IsValid)//实体验证
            {
                if (Request["IsCreateUser"] != null && Request["IsCreateUser"] == "on")
                {
                    if (Request["UserName"] == null || Request["UserPassword"] == null || Request["ConfirmPassword"] == null)
                    {
                        return Json(new CallbackStatus
                        {
                            message = "请填写用户名或密码!",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9_]{2,}$");
                    if (!regex.IsMatch(Request["UserName"].Trim()))
                    {
                        return Json(new CallbackStatus
                        {
                            message = "用户名格式不正确，请以英文、数字做用户名，并且最小4位！",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                    if (Request["ConfirmPassword"].Trim() != Request["UserPassword"].Trim())
                    {
                        return Json(new CallbackStatus
                        {
                            message = "两次输入的密码不一致！",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                    if (ServiceManager.Instance.UserService.Exists(Request["UserName"]))
                    {
                        return Json(new CallbackStatus
                        {
                            message = "已经存在同名用户!",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                }
                //添加职员
                model.DeletionStateCode = 0;
                string id = ServiceManager.Instance.OrganizeService.AddStaff(model, out statuCode, out statuMessage);
                model.Id = Convert.ToInt32(id);
                if (statuCode == StatusCode.OKAdd.ToString())
                {
                    //如果同时创建用户，则在用户表中也同时保存相关ID
                    if (Request["IsCreateUser"] != null && Request["IsCreateUser"] == "on")
                    {
                        Base_User userDetail = new Base_User();
                        userDetail.UserName = Request["UserName"];
                        userDetail.UserPassword = Request["UserPassword"];
                        if (!string.IsNullOrEmpty(Request["CompanyId"]))
                            userDetail.CompanyId = int.Parse(Request["CompanyId"]);
                        userDetail.CompanyName = Request["CompanyName"];
                        if (!string.IsNullOrEmpty(Request["DepartmentId"]))
                            userDetail.DepartmentId = int.Parse(Request["DepartmentId"]);
                        userDetail.DepartmentName = Request["DepartName"];
                        userDetail.RealName = model.RealName;
                        userDetail.Enabled = 1;
                        string outCode = string.Empty, outMessage = string.Empty;//返回状态码，状态信息
                        string userID = ServiceManager.Instance.UserService.AddUser(userDetail, out outCode, out outMessage);
                        //添加用户角色关系 WS 2011.11.29
                        if (outCode == "OKAdd")
                        {
                            if (!String.IsNullOrEmpty(Request["RoleIDs"]))
                            {
                                string userRoleStatusCode = string.Empty, userRoleStatusMsg = string.Empty;
                                //添加该用户的所选角色
                                string[] rolelist = ServiceManager.Instance.UserService.GetUserRoleIds(userID);//获取该用户所属的角色
                                //UserService.RemoveUserFromRole(userID, StringHelper.listToString(rolelist), out outCode, out outMessage);
                                ServiceManager.Instance.UserService.AddUserToRole(userID, Request["RoleIDs"], out userRoleStatusCode, out userRoleStatusMsg);
                            }
                        }
                        //TODO:判断用户是否添加成功并给予前台提示 WS 2011.10.27
                    }
                }
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode == "OKAdd" ? "200" : "300",
                callbackType = "Create",
                data = model
            });
        }

        //编辑组织机构中的职员
        // GET: /Permission/Organize/EditStaff/5
        public ActionResult EditStaff(int id)
        {
            //编辑职员与新建职员分开，根据关系表，显示所有所属部门、所属岗位 已分开已修复
            DotNet.Model.MyEntity.Base_Staff model = ServiceManager.Instance.OrganizeService.GetStaffEntityById(id.ToString());
            ViewBag.CompanyName = model.CompanyId == null ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(model.CompanyId.ToString()).FullName;
            ViewBag.DepartmentName = model.DepartmentId == null ? "" : ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(model.DepartmentId.ToString()).FullName;
            //ViewBag.DutyName = ServiceManager.Instance.OrganizeService.GetDutyEntityById(model.DutyId.ToString()).Name;
            //ViewBag.WorkgroupName = model.WorkgroupId != null ? ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(model.CompanyId.ToString()).FullName : "";
            ViewBag.Flag = "Edit";
            //ViewBag.IsCreateUser = model.UserId == null ? "0" : "1";//标记此职员是否已创建用户
            //填充下拉框数据
            List<Base_Gender> sexList;
            List<Base_Title> titleList;
            DropDownData(out sexList, out titleList);
            ViewBag.GenderList = sexList;
            ViewBag.TitleList = titleList;
            //角色 WS 2011.11.29
            //TODO: 考虑到要取某个职员的用户ID，而职员表上没有保存用户ID，以后优化权限系统时可以考虑
            Base_User userDetail = ServiceManager.Instance.UserService.GetDTByUserName(model.UserName);
            if (userDetail != null && !String.IsNullOrEmpty(userDetail.UserName))
            {
                string[] roleListIDs = ServiceManager.Instance.UserService.GetUserRoleIds(userDetail.Id.ToString());
                string roleListID = StringHelper.listToString(roleListIDs);//角色ID列表
                ViewData["roleListID"] = roleListID;
                string RoleNames = String.Empty;
                if (roleListID.Length > 0)
                {
                    for (int i = 0; i < roleListIDs.Count(); i++)
                    {
                        RoleNames += ServiceManager.Instance.RoleService.GetRoleEntityByID(roleListIDs[i]).Realname + ",";
                    }
                    RoleNames = RoleNames.Substring(0, RoleNames.Length - 1);
                }
                ViewBag.RoleNames = RoleNames;
            }
            return View(model);
        }

        //编辑职员的提交处理
        // POST: /Permission/Organize/StaffEditing/5
        [HttpPost]
        public ActionResult StaffEditing(DotNet.Model.MyEntity.Base_Staff model)
        {
            string statuCode = string.Empty;
            string statuMessage = string.Empty;
            if (ModelState.IsValid)//实体验证
            {
                if (Request["IsCreateUser"] != null && Request["IsCreateUser"] == "on")
                {
                    if (Request["UserName"] == null || Request["UserPassword"] == null || Request["ConfirmPassword"] == null)
                    {
                        return Json(new CallbackStatus
                        {
                            message = "请填写用户名或密码!",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9_]{2,}$");
                    if (!regex.IsMatch(Request["UserName"].Trim()))
                    {
                        return Json(new CallbackStatus
                        {
                            message = "用户名格式不正确，请以英文、数字做用户名，并且最小4位！",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                    if (Request["ConfirmPassword"].Trim() != Request["UserPassword"].Trim())
                    {
                        return Json(new CallbackStatus
                        {
                            message = "两次输入的密码不一致！",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                    if (ServiceManager.Instance.UserService.Exists(Request["UserName"]))
                    {
                        return Json(new CallbackStatus
                        {
                            message = "已经存在同名用户!",
                            statusCode = "300",
                            callbackType = "Create",
                            data = model
                        });
                    }
                }
                model.DeletionStateCode = 0;
                model.UserName = ServiceManager.Instance.OrganizeService.GetStaffEntityById(model.Id.ToString()).UserName;
                int id = ServiceManager.Instance.OrganizeService.EditStaff(model, out statuCode, out statuMessage);
                //model.Id = id;
                if (statuCode == StatusCode.OKUpdate.ToString())
                {
                    //若有用户账号，则更新用户信息内的用户姓名（其它没有要更新的） WS 2011.10.31
                    if (!String.IsNullOrEmpty(model.UserName))
                    {
                        Base_User userDetail = ServiceManager.Instance.UserService.GetDTByUserName(model.UserName);
                        if (userDetail != null)
                        {
                            userDetail.RealName = model.RealName;
                            string userStatusCode = string.Empty;
                            string userStatusMsg = string.Empty;
                            ServiceManager.Instance.UserService.UpdateUser(userDetail, out userStatusCode, out userStatusMsg);
                        }
                    }
                    //如果同时创建用户，则在用户表中也同时保存相关ID
                    if (Request["IsCreateUser"] != null && Request["IsCreateUser"] == "on")
                    {
                        Base_User userDetail = new Base_User();
                        userDetail.UserName = Request["UserName"];
                        userDetail.UserPassword = Request["UserPassword"];
                        if (!string.IsNullOrEmpty(Request["CompanyId"]))
                            userDetail.CompanyId = int.Parse(Request["CompanyId"]);
                        //userDetail.CompanyName = Request["CompanyName"];
                        if (!string.IsNullOrEmpty(Request["DepartmentId"]))
                            userDetail.DepartmentId = int.Parse(Request["DepartmentId"]);
                        //userDetail.DepartmentName = Request["DepartName"];
                        userDetail.RealName = model.RealName;
                        userDetail.Enabled = 1;
                        string outCode = string.Empty, outMessage = string.Empty;//返回状态码，状态信息
                        string userID = ServiceManager.Instance.UserService.AddUser(userDetail, out outCode, out outMessage);
                        //添加用户角色关系 WS 2011.11.29
                        if (outCode == "OKAdd")
                        {
                            if (!String.IsNullOrEmpty(Request["RoleIDs"]))
                            {
                                string userRoleStatusCode = string.Empty, userRoleStatusMsg = string.Empty;
                                //添加该用户的所选角色
                                string[] rolelist = ServiceManager.Instance.UserService.GetUserRoleIds(userID);//获取该用户所属的角色
                                //UserService.RemoveUserFromRole(userID, StringHelper.listToString(rolelist), out outCode, out outMessage);
                                ServiceManager.Instance.UserService.AddUserToRole(userID, Request["RoleIDs"], out userRoleStatusCode, out userRoleStatusMsg);
                            }
                        }
                        //TODO:判断用户是否添加成功并给予前台提示 WS 2011.10.27
                    }
                }
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode == "OKUpdate" ? "200" : "300",
                callbackType = "Edit",
                data = model
            });
        }

        /// <summary>
        /// 职员签名上传页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdatePic(string id)
        {
            ViewBag.ID = id;
            return View();
        }

        /// <summary>
        /// 职员签名上传，成功返回文件流，并显示签名图
        /// </summary>
        /// <param name="id"></param>
        /// <param name="picture"></param>
        /// <returns></returns>
        public ActionResult UpdatingPic(string id, HttpPostedFileBase FileData)
        {
            int dotIndex = FileData.FileName.LastIndexOf('.');
            string extStrs = ".png|.jpg|.bmp|.jpeg|.gif";
            if (!extStrs.Contains(FileData.FileName.Substring(dotIndex).ToLower()))
            {
                return Json(new CallbackStatus
                    {
                        message = "上传格式不正确",
                        statusCode = "300",
                        callbackType = "UploadFile"
                    });
            }
            DotNet.Model.MyEntity.Base_Staff detail = ServiceManager.Instance.OrganizeService.GetStaffEntityById(id);

            string statuCode = string.Empty;
            string statuMessage = string.Empty;

            if (detail != null)
            {
                try
                {
                    byte[] newByte = new byte[FileData.ContentLength];
                    System.IO.Stream fileStream = FileData.InputStream;
                    fileStream.Read(newByte, 0, FileData.ContentLength);
                    detail.Picture = newByte;
                    ServiceManager.Instance.OrganizeService.EditStaff(detail, out statuCode, out statuMessage);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode,
                callbackType = "UploadFile"
            });
        }
        /// <summary>
        /// 显示签名
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowPic(string id)
        {
            DotNet.Model.MyEntity.Base_Staff detail = ServiceManager.Instance.OrganizeService.GetStaffEntityById(id);

            if (detail != null && detail.Picture != null)
            {
                return File(detail.Picture, @"image/jpeg");
            }
            else
                return null;
        }
        #endregion
        //删除组织机构、岗位、职员
        // Post: /Permission/Organize/Delete/5
        [HttpPost]
        public ActionResult Delete(string id)
        {
            string statuCode = "300";
            string statuMessage = "删除失败！";
            string flag = string.Empty;
            if (id.StartsWith("C_"))
            {
                id = id.Remove(0, 2);
                ServiceManager.Instance.OrganizeService.Delete(id, out statuCode, out statuMessage);
                if (statuCode == "200" && !UserService.CurrUserInfo.IsAdministrator)
                {
                    //移除权限
                    string state = string.Empty;
                    string Message = string.Empty;
                    int curRoleID = ServiceManager.Instance.RoleService.GetRoleID();
                    if (curRoleID != 0)
                        ServiceManager.Instance.RoleService.RevokeRoleOrganizeScopes(curRoleID.ToString(), id, out state, out Message);
                }
                flag = "organize";
            }
            //else
            //{
            //    string[] arr_str = id.Split('_');
            //    ServiceManager.Instance.OrganizeService.DeteleUser(arr_str[0],int.Parse(arr_str[3]),int.Parse(arr_str[2]), out statuCode, out statuMessage);
            //    flag = "staff";
            //}
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode,
                callbackType = flag
            });
        }

        //选择组织机构的加载Action
        public ActionResult SelectOrganize(string id)
        {
            if (id.Contains("_"))
            {
                ViewBag.Flag = id.Substring(0, 1);
                ViewBag.TempFlag = id.Substring(2);
            }
            if (Request["receiveId"] != null) ViewBag.ReceiveId = Request["receiveId"];
            return View();
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateUser()
        {
            //获得角色数据
            List<Base_Role> roleList = ServiceManager.Instance.RoleService.GetDT();
            ViewBag.rolelist = roleList;
            return View();
        }
        /// <summary>
        /// 创建用户的提交处理
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserCreating(Base_User user)
        {
            string outCode = string.Empty, outMessage = string.Empty;//返回状态码，状态信息
            if (ModelState.IsValid)
            {
                string userId = ServiceManager.Instance.UserService.AddUser(user, out outCode, out outMessage);
                if (!string.IsNullOrEmpty(userId))
                    user.Id = Convert.ToInt32(userId);
            }
            return Json(new CallbackStatus
            {
                message = outMessage,
                statusCode = outCode.ToLower() == "okadd" ? "200" : "300",
                callbackType = user.Id + "," + user.UserName
            });
        }

        #region WS 2010.10.21添加

        /// <summary>
        /// 为组织机构与岗位建立关系
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="dutyId"></param>
        /// <returns></returns>
        public ActionResult CreateConnectionOrgAndDuty(string orgId, string dutyId, string dutyName)
        {
            string outCode = string.Empty, outMessage = string.Empty;//返回状态码，状态信息
            ServiceManager.Instance.OrganizeService.CreateConnectionOrgAndDuty(dutyId, orgId, out outCode, out outMessage);
            OrganizeDutyEntity ode = new OrganizeDutyEntity();
            ode.Id = "D_" + dutyId + "_" + orgId;
            ode.ParentId = "C_" + orgId;
            ode.Name = dutyName;
            ode.Mark = "Duty";
            ode.iconSkin = "iCandyDuty";
            ode.Type = "2";
            return Json(new CallbackStatus
            {
                message = outMessage,
                statusCode = outCode,
                callbackType = "Create",
                data = ode
            });
        }
        //移除岗位
        //参数id的数据形式是D_岗位ID_组织机构id
        public ActionResult RemoveConnectionOrgAndDuty(string id)
        {
            string outCode = string.Empty, outMessage = string.Empty;//返回状态码，状态信息
            string[] arr_str = id.Split('_');
            ServiceManager.Instance.OrganizeService.RemoveDuty(arr_str[1], arr_str[2], out outCode, out outMessage);
            return Json(new CallbackStatus
            {
                message = outMessage,
                statusCode = outCode,
                callbackType = "organize"
            });
        }

        /// <summary>
        /// 添加已有职员（添加职员到岗位、添加职员到部门）
        /// </summary>
        /// <param name="dutyId"></param>
        /// <param name="staffId"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public ActionResult CreateConnectionDutyAndStaff(string dutyId, string staffId, string orgId)
        {
            string outCode = string.Empty, outMessage = string.Empty;//返回状态码，状态信息
            ServiceManager.Instance.OrganizeService.CreateConnectionDutyAndStaff(dutyId, staffId.Substring(2), orgId, out outCode, out outMessage);
            return Json(new CallbackStatus
            {
                message = outMessage,
                statusCode = outCode,
                callbackType = "close"
            });
        }
        #endregion

        #region qyj 2013-7-17  增加选择机构与人员功能
        /// <summary>
        /// 增加选择机构与人员功能
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectOrganizePerson()
        {
            return View();
        }
        #endregion
    }

    /// <summary>
    /// 单位类型 WS 2011.11.10
    /// </summary>
    public class OrgType
    {
        public string Type { get; set; }
        public string Name { get; set; }
    }
}
